// 获取所有学生，并渲染到页面
function students() {
    axios.get('/student/list').then(({ data }) => {
        let arr = []
        data.data.forEach(item => {
            arr.push(`
            <tr>
            <th scope="row">${item.id}</th>
            <td>${item.name}</td>
            <td>${item.sex}</td>
            <td>${item.age}</td>
            <td>${item.group}</td>
            <td>${item.phone}</td>
            <td>${item.salary}</td>
            <td>${item.truesalary}</td>
            <td>${item.province}${item.city}${item.county}</td>
            <td>
          <button data-id="${item.id}" type="button" class="btn btn-primary btn-sm">修改</button>
          <button data-id="${item.id}" type="button" class="btn btn-danger btn-sm">删除</button>
        </td>
      </tr>
            `)
        });
        $('tbody').html(arr.join(''))
    })
}
students()
// 获取省
axios.get('/geo/province').then(({ data }) => {
    let arr = ['<option selected value="">--省--</option>']
    data.forEach(item => {
        arr.push(`<option value="${item}">${item}</option>`)
    })
    $('select[name=province]').html(arr.join(''))

})
// 获取市
$('select[name="province"]').change(function () {
    $('select[name="county"]').html('<option selected="" value="">--县--</option>')
    let pname = $(this).val()
    if (pname) {
        axios.get('/geo/city', { params: { pname } }).then(({ data }) => {
            let arr = ['<option selected="" value="">--市--</option>']
            data.forEach(item => {
                arr.push(`
                <option value="${item}">${item}</option>
                `)
            })
            $('select[name="city"]').html(arr.join(''))
        })
    }

})
// 获取县
// 3. 当市切换的时候，获取对应的县
$('select[name=city]').on('change', function () {
    let pname = $(this).parent().prev().find('select').val();
    let cname = $(this).val();
    // console.log(pname, cname);
    // return;
    if (pname && cname) {
        axios.get('/geo/county', { params: { pname, cname } }).then(({ data: res }) => {
            // console.log(res);
            let arr = [`<option selected value="">--县--</option>`];
            res.forEach(item => {
                arr.push(`<option value="${item}">${item}</option>`);
            });
            $('select[name=county]').html(arr.join(''));
        })
    }
})

// 表单验证
function student() {
    return {
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '姓名不能为空',
                    },
                    stringLength: {
                        min: 2,
                        max: 10,
                        message: '姓名长度2~10位'
                    }
                }
            },
            age: {
                validators: {
                    notEmpty: {
                        message: '年龄不能为空',
                    },
                    greaterThan: {
                        value: 18,
                        message: '年龄不能小于18岁'
                    },
                    lessThan: {
                        value: 60,
                        message: '年龄不能超过60岁'
                    }
                }
            },
            sex: {
                validators: {
                    choice: {
                        min: 1,
                        max: 1,
                        message: '请选择性别'
                    }
                }
            },
            group: {
                validators: {
                    notEmpty: {
                        message: '组号不能为空',
                    },
                    regexp: {
                        regexp: /^\d{1,2}$/,
                        message: '请选择有效的组号'
                    }
                }
            },
            phone: {
                validators: {
                    notEmpty: {
                        message: '手机号不能为空',
                    },
                    regexp: {
                        regexp: /^1\d{10}$/,
                        message: '请填写有效的手机号'
                    }
                }
            },
            salary: {
                validators: {
                    notEmpty: {
                        message: '期望薪资不能为空',
                    },
                    greaterThan: {
                        value: 800,
                        message: '期望薪资不能低于800'
                    },
                    lessThan: {
                        value: 100000,
                        message: '期望薪资不能高于100000'
                    }
                }
            },
            truesalary: {
                validators: {
                    notEmpty: {
                        message: '实际薪资不能为空',
                    },
                    greaterThan: {
                        value: 800,
                        message: '实际薪资不能低于800'
                    },
                    lessThan: {
                        value: 100000,
                        message: '实际薪资不能高于100000'
                    }
                }
            },
            province: {
                validators: {
                    notEmpty: {
                        message: '省份必填',
                    },
                }
            },
            city: {
                validators: {
                    notEmpty: {
                        message: '市必填',
                    },
                }
            },
            county: {
                validators: {
                    notEmpty: {
                        message: '县必填',
                    },
                }
            },
        }
    }
}
// 添加学生
$('.add-form').bootstrapValidator(student()).on('success.form.bv', function (e) {
    e.preventDefault();
    let data = $(this).serialize();

    axios.post('/student/add', data).then(({ data: res }) => {
        // console.log(res);
        if (res.code === 0) {
            toastr.success(res.message);
            students();
            $('#addModal').modal('hide') // 这个是关闭模态框（弹出框）的意思
            $('.btn-secondary').click()   //触发重置按钮，清空表单内容
        }
    })
});
// 删除学生
$('tbody').on('click', '.btn-danger', function () {
    // 判断是否删除
    if (!confirm('确定删除吗？')) return;
    let id = $(this).data('id')
    axios.delete('/student/delete', { params: { id } }).then(({ data }) => {
        if (data.code === 0) {
            toastr.success(data.message);
            students()
        }
    })
})
// 修改
$('tbody').on('click', '.btn-primary', function () {

    let id = $(this).data('id')
    axios.get('/student/one', { params: { id } }).then(({ data: res }) => {

        let { code, data } = res
        if (code === 0) {
            // 数据回填
            $('#updateModal input[name=id]').val(id)
            $('#updateModal input[name=name]').val(data.name)
            $('#updateModal input[name=age]').val(data.age)
            $('#updateModal input[name=phone]').val(data.phone)
            $('#updateModal input[name=salary]').val(data.salary)
            $('#updateModal input[name=truesalary]').val(data.truesalary)
            $(`#updateModal input[name=sex][value=${data.sex}]`).prop('checked', true)
            $(`#updateModal select[name=group]`).find(`option[value=${data.group}]`).prop('selected', true)
            $(`#updateModal select[name=province]`).find(`option[value=${data.province}]`).prop('selected', true)
            $(`#updateModal select[name=city]`).html(`<option selected value="${data.city}">${data.city}</option>`)
            $(`#updateModal select[name=county]`).html(`<option selected value="${data.county}">${data.county}</option>`)

            $('#updateModal').modal('show')
        }
    })
})
$('.update-form').bootstrapValidator(student()).on('success.form.bv', function (e) {
    e.preventDefault();

    let data = $(this).serialize()

    axios.put('/student/update', data).then(({ data }) => {
        if (data.code === 0) {
            toastr.success(data.message);
            students();
            $('#updateModal').modal('hide') // 这个是关闭模态框（弹出框）的意思
        }
    })
});